<template>
	<el-upload v-bind="uploadConfig" :file-list="uploadFiles" :accept="uploadAccept">
		<el-button size="small" type="primary" :disabled="disabled">点击上传</el-button>
		<template slot="file" slot-scope="{ file }">
			<i class="icon" :style="file | fileIconPosition"></i>
			<h4>{{ file | formatFileName }}</h4>
			<template v-if="!disabled">
				<el-button type="text" icon="el-icon-delete" @click="handleDeleteFile(file)" />
				<el-progress v-bind="progressConfig" :percentage="progressPercentage(file)" :color="progressColor(file)" />
			</template>
		</template>
	</el-upload>
</template>

<script>
import Vue from 'vue';
import lodash from 'lodash';
import authBtns from '@/mixins/authButtons';
import emitter from 'element-ui/src/mixins/emitter';
const baseUrl = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
const getFileSuffix = (filename) => {
	if (!lodash.isEmpty(filename)) {
		let len = filename.length;
		let index = lodash.lastIndexOf(filename, '.');
		if (index === -1 || index === len - 1) return '';
		return filename.slice(index + 1)?.toLowerCase() || '';
	} else {
		return '';
	}
};
export default {
	mixins: [emitter],
	name: 'swFileUploader',
	props: {
		value: { type: String, default: '' },
		type: { type: String, default: '1' },
		accept: { type: String, default: '' },
		disabled: { type: Boolean, default: false }
	},
	data() {
		let Authorization = this.$session.get('token');
		let uploadParams = { showType: '5', type: '1' };
		let commonAuths = lodash(authBtns.commonAuth).find({ field: 'upload' });
		console.log(this.commonAuths);
		return {
			fileValue: this.value,
			uploadConfig: {
				ref: 'upload',
				multiple: true,
				// autoUpload: false,
				data: uploadParams,
				onChange: this.handleUploadChange,
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleBeforeUpload,
				action: `${baseUrl}/tbSysAttachment/upload`,
				class: ['sw_file_uploader', { disabled: this.disabled }],
				headers: { Authorization, userButton: lodash.get(commonAuths, 'id') }
			},
			progressConfig: { strokeWidth: 1, showText: false },
			uploadFiles: []
		};
	},
	computed: {
		uploadAccept() {
			let acceptArr = this.accept.split(',');
			return acceptArr.map((n) => `.${n}`).join();
		},
		uploadSize() {
			let size = parseInt(this.size);
			let ratios = this.ratio.split(':');
			let ratioNumber = parseInt(ratios[1]) / parseInt(ratios[0]);
			return { width: `${size}px`, height: `${size * ratioNumber}px` };
		},
		cropperRatio() {
			return this.ratio.split(':').join(',');
		}
	},
	filters: {
		formatFileName(file) {
			let suffix = getFileSuffix(file.name);
			return !suffix ? `${file.name}.${file.suffix}` : file.name;
		},
		fileIconPosition(file) {
			let suffix = getFileSuffix(file.name);
			let fileSuffix = !suffix ? file.suffix : suffix;
			if (['doc', 'docx'].includes(fileSuffix)) {
				return { 'background-position': 'center 0' };
			} else if (['xls', 'xlsx'].includes(fileSuffix)) {
				return { 'background-position': 'center -25px' };
			} else if (['ppt', 'pptx'].includes(fileSuffix)) {
				return { 'background-position': 'center -50px' };
			} else if (fileSuffix === 'pdf') {
				return { 'background-position': 'center -75px' };
			} else if (fileSuffix === 'txt') {
				return { 'background-position': 'center -100px' };
			} else if (['mp4', 'avi', 'mov', 'flv', 'mkv', 'rmvb', 'wmv'].includes(fileSuffix)) {
				return { 'background-position': 'center -150px' };
			} else if (['png', 'jpg', 'gif', 'svg'].includes(fileSuffix)) {
				return { 'background-position': 'center -125px' };
			} else if (['mp3', 'aac', 'ogg', 'flac', 'wav'].includes(fileSuffix)) {
				return { 'background-position': 'center -175px' };
			} else if (['zip', 'rar', '7z'].includes(fileSuffix)) {
				return { 'background-position': 'center -200px' };
			} else {
				return { 'background-position': 'center -225px' };
			}
		}
	},
	watch: {
		value(val) {
			this.fileValue = val;
		},
		fileValue(val) {
			this.$emit('input', val);
			this.dispatch('ElFormItem', 'el.form.change', [val]);
			if (!!val && val !== '-1' && val.isJSON()) {
				this.uploadFiles = JSON.parse(val);
			} else {
				this.uploadFiles = [];
			}
		},
		uploadFiles(arr) {
			let successFile = lodash.filter(arr, { status: 'success' });
			if (arr.length === successFile.length) {
				let dataArr = lodash.map(arr, (n) => lodash.omit(n, ['uid']));
				this.fileValue = JSON.stringify(dataArr);
			}
		}
	},
	methods: {
		progressColor(file) {
			if (file.status === 'success') {
				return '#67C23A';
			} else if (file.status === 'error') {
				return '#F56C6C';
			} else {
				return '';
			}
		},
		progressPercentage(file) {
			return file.status === 'success' && !file.percentage ? 100 : file.percentage;
		},

		//上传之前
		handleBeforeUpload(file) {
			return true;
		},
		//上传成功
		handleUploadSuccess(res, file, fileList) {
			let result = this.$detailData(res.data);
			file.status = lodash.isEmpty(result) ? 'error' : file.status;
		},
		//上传变化
		handleUploadChange(file, fileList) {
			this.uploadFiles = fileList.map((item) => {
				if (!item.response) {
					return item;
				} else {
					let fileData = lodash.pick(item, ['uid', 'status']);
					let result = this.$detailData(item.response.data);
					if (lodash.isEmpty(result)) {
						return item;
					} else {
						let fields = ['id', 'newName', 'absoluteAddr'];
						let datas = lodash.pick(result, fields);
						fileData['suffix'] = result.attrSuffixStr;
						fileData['url'] = result.originalAddr;
						fileData['name'] = result.oldName;
						return { ...fileData, ...datas };
					}
				}
			});
		},

		handleDeleteFile(file) {
			let index = lodash.findIndex(this.uploadFiles, { uid: file.uid });
			this.$delete(this.uploadFiles, index);
		}
	}
};
</script>

<style lang="scss" scoped>
.sw_file_uploader {
	position: relative;
	overflow: hidden;
	line-height: 1;
	&.disabled:deep(.el-upload-list__item) {
		color: #909399;
		&:hover {
			background-color: transparent;
		}
	}
	&:deep(.el-upload-list__item) {
		display: flex;
		align-items: center;
		border: 1px solid #e4e7ed;
		border-radius: 2px;
		position: relative;
		margin-bottom: 0;
		transition: none;
		cursor: pointer;
		height: 40px;
		padding: 0;
		i.icon {
			width: 20px;
			height: 25px;
			flex-shrink: 0;
			background-image: url('');
			background-repeat: no-repeat;
			background-size: 20px auto;
			margin-left: 8px;
		}
		h4 {
			flex: 1;
			font-size: 14px;
			line-height: 20px;
			font-weight: normal;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
			margin: 0 8px;
		}
		.el-progress {
			top: -1px;
		}
		.el-button {
			flex-shrink: 0;
			display: none;
			padding: 10px;
		}
		&:hover .el-button {
			display: flex;
		}
	}
}
</style>
